<?php

/*
 * Articulo
 */

class Articulo implements iPersistente, iJson{
    
    private $id , $nombre , $broker, $yaPersistido;
    
    public function getId() {
        return $this->id;
    }

    public function setId($id) {
        $this->id = $id;
    }

    public function getNombre() {
        return $this->nombre;
    }

    public function setNombre($nombre) {
        $this->nombre = $nombre;
    }

    public function getBroker() {
        return $this->broker;
    }

    public function setBroker($broker) {
        $this->broker = $broker;
    }

    public function getYaPersistido() {
        return $this->yaPersistido;
    }

    public function setYaPersistido($yaPersistido) {
        $this->yaPersistido = $yaPersistido;
    }

    public function __construct($enJson = null, $i = '', $n = '',$boolP = false) {        
      if ( $enJson <> null ){
        $this->checkJson($enJson);
        $valores = json_decode($enJson);
        $this->id = $valores->id;
        $this->nombre = $valores->nombre;
        $this->broker = new Broker($this);
        $this->yaPersistido = $valores->yaPersistido;      
      }else{
        $this->id = $i;
        $this->nombre = $n;
        $this->broker = new Broker($this);
        $this->yaPersistido = $boolP;
      }       
    }
    
    public function borrar() {
        $this->broker->borrar("DELETE FROM articulo WHERE id = \"$this->id\"");
    }
    public function guardar() {
        if ( $this->yaPersistido == 'true' ){
            $this->broker->guardar("UPDATE articulo set nombre = \"$this->nombre\" WHERE id = \"$this->id\"");
        }else{
            $this->broker->guardar("INSERT INTO articulo (nombre) VALUES (\"$this->nombre\")");
            $this->yaPersistido = true;
            $this->id = $this->broker->UltimoID();
        }
    }
    public function obtenerTodos() {
        return null;        
    }
    public function obtenerXid($id) {
        return null;
    }

    public function toJson() {
        $ret = new stdClass();
        $ret->id = $this->id;
        $ret->nombre = $this->nombre;
        $ret->yaPersistido = $this->yaPersistido;
        return $ret;
    }

    public function checkJson($s) {
        $elem = json_decode($s);
        
        if ( !isset($elem->id) || !isset($elem->nombre) || !isset($elem->yaPersistido) ){
            throw new Exception("Obj. Articulo JSon Invalido");
        }      
    }
}
?>
